/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the seckill4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.jalonjia.seckill.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jalonjia.seckill.admin.api.entity.SysDictItem;
import com.jalonjia.seckill.common.core.constant.CacheConstants;
import com.jalonjia.seckill.common.security.util.SecurityUtils;
import com.jalonjia.seckill.core.entity.SeckillActivity;
import com.jalonjia.seckill.core.entity.SeckillOrder;
import com.jalonjia.seckill.core.entity.SeckillTarget;
import com.jalonjia.seckill.core.mapper.SeckillActivityMapper;
import com.jalonjia.seckill.core.mapper.SeckillOrderMapper;
import com.jalonjia.seckill.core.mapper.SeckillTargetMapper;
import com.jalonjia.seckill.core.service.SeckillActivityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 秒杀活动
 *
 * @author 贾晓超
 * @date 2022-05-05 20:56:44
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SeckillActivityServiceImpl extends ServiceImpl<SeckillActivityMapper, SeckillActivity> implements SeckillActivityService {
	private final RedisTemplate<String, Object> redisTemplate;
	private final StringRedisTemplate stringRedisTemplate;
	private final SeckillTargetMapper seckillTargetMapper;
	private final SeckillOrderMapper seckillOrderMapper;

	@Override
	public List<SysDictItem> getActivityDict() {
		List<SeckillActivity> seckillActivities;
		if (SecurityUtils.isAdmin()) {
			seckillActivities = query().list();
		} else {
			// 查寻用户创建的和用户参与的
			List<Long> orderList = seckillOrderMapper.selectList(new QueryWrapper<SeckillOrder>().eq("create_by", SecurityUtils.username()))
					.stream().map(SeckillOrder::getActivityNo).collect(Collectors.toList());
			seckillActivities = query().eq("create_by", SecurityUtils.getUser().getUsername())
					.or().in("id", orderList).list();
		}
		return seckillActivities.stream().map(activity -> {
			SysDictItem sysDictItem = new SysDictItem();
			sysDictItem.setValue(activity.getId().toString());
			sysDictItem.setLabel(activity.getTitle());
			sysDictItem.setType("activityDicts");
			return sysDictItem;
		}).collect(Collectors.toList());
	}

	@Override
	public void warmupActivity(List<SeckillActivity> activityList) {
		LocalDateTime now = LocalDateTime.now();
		activityList.forEach(activity -> {
			// 缓存锁
			String warmupKey = CacheConstants.ACTIVITY_WARMUP + activity.getId();
			if(!activityWarmingUp(activity.getId())){
				log.info("预热秒杀活动：{}", activity.getId());
				redisTemplate.opsForValue().increment(warmupKey);
				// 过期时间
				long ttl = now.until(activity.getEndTime(), ChronoUnit.SECONDS);
				String activityKey = CacheConstants.SECKILL_ACTIVITY + activity.getId();
				// 预热秒杀活动
				redisTemplate.opsForValue().set(activityKey, activity, ttl, TimeUnit.SECONDS);
				// 预热秒杀对象
				SeckillTarget seckillTarget = seckillTargetMapper.selectById(activity.getTargetNo());
				String targetNumKey = CacheConstants.TARGET_NUM + activity.getTargetNo();
				stringRedisTemplate.opsForValue().set(targetNumKey, seckillTarget.getRemainNum().toString(), ttl, TimeUnit.SECONDS);
				// 解除缓存锁
				redisTemplate.opsForValue().decrement(warmupKey);
			}
		});
	}

	@Override
	public boolean activityWarmingUp(Long id){
		String warmupKey = CacheConstants.ACTIVITY_WARMUP + id;
		return redisTemplate.opsForValue().increment(warmupKey, 0L) > 0L;
	}

	@Override
	public boolean duringActivity(SeckillActivity activity){
		LocalDateTime now = LocalDateTime.now();
		if (now.isBefore(activity.getStartTime()) || now.isAfter(activity.getEndTime())) {
			return false;
		}
		return true;
	}
}
